package fr.utbm.gi.in56.ads;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.utbm.gi.in56.database.DatabaseServlet;
import fr.utbm.gi.in56.error.ErrorType;
import fr.utbm.gi.in56.vehicle.BrandEntry;
import fr.utbm.gi.in56.vehicle.ModelEntry;
import fr.utbm.gi.in56.vehicle.VehicleManager;

/**
 * Servlet implementation class AdServlet
 * 
 * @author Adrien Hoffer & Tarik Belabbas
 */
@WebServlet("/AdServlet")
public class AdServlet extends DatabaseServlet
{
	private static final long	serialVersionUID	= 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public AdServlet()
	{
		super();
	}
	
	/**
	 * Retrieves and set car/energy lists as request attribute.
	 * 
	 * @param request the servlet request
	 * @param response the servlet response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected ErrorType forwardEnergyAndCarLists( HttpServletRequest request,
			HttpServletResponse response ) throws ServletException, IOException
	{
		VehicleManager vehicleMg = null;
		try
		{
			vehicleMg = new VehicleManager( getConnection() );
		}
		catch ( SQLException e )
		{
			e.printStackTrace();
			
			return ErrorType.POST_UNABLE_RETRIEVE_CARS_ENERGIES;
		}

		request.setAttribute("energiesList", vehicleMg.getEnergiesList() ); //$NON-NLS-1$
		
		HashMap< BrandEntry, LinkedList< ModelEntry > > vehicleMap =
			vehicleMg.getBrandsAndModels();
		
		// The brand list
		List< BrandEntry > brandList = new ArrayList< BrandEntry >( vehicleMap.keySet() );
		Collections.sort( brandList );
		
		// The list of list of models
		List< List< ModelEntry > > modelLists = new ArrayList< List< ModelEntry > >();
		for ( BrandEntry currentBrand : brandList )
		{
			List< ModelEntry > brandModels = vehicleMap.get( currentBrand );
			
			Collections.sort( brandModels );
			modelLists.add( brandModels );
		}
		
		request.setAttribute("brandList", brandList ); //$NON-NLS-1$
		request.setAttribute("modelLists", modelLists ); //$NON-NLS-1$
		
		return ErrorType.NONE;
	}
}
